/**
 * 描述: 业务逻辑处理 - 单词接口
 * 作者: wz
 * 日期: 2023-12-25
*/


const { querySql, formatTime, innerUploadFile } = require('../utils/index');
const { getWordPronunciation } = require('./common');
const boom = require('boom');
const { body, validationResult } = require('express-validator');
const { 
  CODE_ERROR,
  CODE_SUCCESS, 
} = require('../utils/constant');

// 查询所有单词列表
async function getAllWordList(req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
    next(boom.badRequest(msg));
  } else {

    let { pageSize, pageNo, params } = req.body;
    
    // 默认值
    pageSize = pageSize ? pageSize : 1;
    pageNo = pageNo ? pageNo : 1;

    let query = `select id from sys_allword`;
    let paramsStr = ' where delete_flag=0';
    if( params){
      if( params.word){
        paramsStr += ' and word like \'%' + params.word + '%\'';
      }
      if( params.word_zh){
        paramsStr += ' and word_zh like \'%' + params.word_zh + '%\'';
      }
      if( params.phonetic){
        paramsStr += ' and phonetic like \'%' + params.phonetic + '%\'';
      }
    }

    try{
      let data = await querySql(query + paramsStr)
    	// console.log('任务列表查询===', data);
      if (!data || data.length === 0) {
        res.json({ 
        	code: CODE_SUCCESS, 
        	msg: '暂无数据', 
        	data: null 
        })
      } else {
        // 计算数据总条数
        let total = data.length; 
        // 分页条件 (跳过多少条)
        let n = (pageNo - 1) * pageSize;
        // 拼接分页的sql语句命令
        let query_3 = `select id,word,word_zh,phonetic from sys_allword`;
        query_3 += paramsStr;
        query_3 += ` order by gmt_create desc limit ${n} , ${pageSize}`;
        let result_3 = await querySql(query_3);
        if (!result_3 || result_3.length === 0) {
          res.json({ 
            code: CODE_SUCCESS, 
            msg: '暂无数据', 
            data: null 
          })
        } else {
          res.json({ 
            code: CODE_SUCCESS, 
            msg: '查询数据成功', 
            data: {
              rows: result_3,
              total: total,
              pageNo: parseInt(pageNo),
              pageSize: parseInt(pageSize),
            } 
          })
        }
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '暂无数据', 
        data: err 
      })
    }
  }
}

// 编辑词汇包
async function editWord(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { id, word, word_zh, phonetic} = req.body;
    let query = `update sys_allword set word='${word}'`;
    if( word_zh){
      query += `, word_zh='${word_zh}'`
    }
    if( phonetic){
      query += `, phonetic='${phonetic}'`
    }
    query += ` where id='${id}'`;
    
    try{
      let data = await querySql(query);
      // console.log('编辑设备===', data);
      if (!data || data.length === 0) {
        res.json({ 
          code: CODE_ERROR, 
          msg: '更新数据失败', 
          data: null 
        })
      } else {
        res.json({ 
          code: CODE_SUCCESS, 
          msg: '更新数据成功', 
          data: null 
        })
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '更新数据失败', 
        data: err 
      })
    }
  }
}

// 查询单词信息
async function getWordInfo(req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
    next(boom.badRequest(msg));
  } else {

    let { word='', words=[], book_id=0 } = req.body;
    let query = ``
    if( words.length > 0){
      query += `select word,word_zh,phonetic,book_id from sys_allword`;
      query += ` where word in ('${words.join("','")}')`;
    }
    else{
      query += `select word,word_zh,phonetic,book_id from sys_allword where word='${word}'`;
    }
    try{
      let data = await querySql(query)
    	// console.log('任务列表查询===', data);
      if (!data || data.length === 0) {
        let ret = null;
        if( word){
          ret = await getWordPronunciation(word);
        }
        res.json({ 
        	code: CODE_SUCCESS, 
        	msg: '暂无数据', 
        	data: ret 
        })
      } else {
        let ret = data;
        if( data.length > 1){
          ret = [];
          for( let item of data){
            let index = ret.findIndex( i=>i.word==item.word);
            if( index >= 0){
              if( item.book_id == book_id){
                // book_id一样的优先
                ret[index] = item;
              }
            }else{
              ret.push(item);
            }
          }
        }
        res.json({ 
          code: CODE_SUCCESS, 
          msg: '查询数据成功', 
          data: words.length > 0 ? ret : ret[0]
        })
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '暂无数据', 
        data: err 
      })
    }
  }
}

module.exports = {
  getAllWordList,
  editWord,
  getWordInfo,
}
